// 存储工具模块

// 获取用户设置
export async function getSettings() {
  return new Promise((resolve) => {
    chrome.storage.sync.get(
      ["apiKey", "targetLang", "displayMode"],
      (result) => {
        resolve({
          apiKey: result.apiKey || "sk-5cc44347435841848718d510310c6868",
          targetLang: result.targetLang || "zh",
          displayMode: result.displayMode || "replace",
        });
      }
    );
  });
}

// 保存用户设置
export async function saveSettings(settings) {
  return new Promise((resolve, reject) => {
    try {
      chrome.storage.sync.set(settings, () => {
        if (chrome.runtime.lastError) {
          reject(new Error(chrome.runtime.lastError.message));
        } else {
          resolve(true);
        }
      });
    } catch (error) {
      reject(error);
    }
  });
}

// 存储翻译结果
export async function storeTranslation(content, tabId) {
  return new Promise((resolve, reject) => {
    try {
      const data = {
        translatedContent: content,
        timestamp: Date.now(),
      };

      // 使用本地存储，不是同步存储
      chrome.storage.local.set(
        {
          [`translation_${tabId}`]: data,
        },
        () => {
          if (chrome.runtime.lastError) {
            reject(new Error(chrome.runtime.lastError.message));
          } else {
            resolve(true);
          }
        }
      );
    } catch (error) {
      reject(error);
    }
  });
}

// 获取翻译结果
export async function getTranslation(tabId) {
  return new Promise((resolve) => {
    chrome.storage.local.get([`translation_${tabId}`], (result) => {
      const data = result[`translation_${tabId}`];
      if (data && Date.now() - data.timestamp < 30 * 60 * 1000) {
        // 30分钟内的翻译缓存
        resolve(data.translatedContent);
      } else {
        resolve(null);
      }
    });
  });
}

// 清除翻译结果
export async function clearTranslation(tabId) {
  return new Promise((resolve) => {
    chrome.storage.local.remove([`translation_${tabId}`], () => {
      resolve(true);
    });
  });
}
